package com.pro01.backend.mapper;

import com.pro01.backend.pojo.UserPromotion;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserPromotionMapper {

    // 插入用户领取的奖励
    @Insert("INSERT INTO user_promotions (user_id, torrent_id, promotion_type, bonus_credit, bonus_upload, bonus_download) " +
            "VALUES (#{userId}, #{torrentId}, #{promotionType}, #{bonusCredit}, #{bonusUpload}, #{bonusDownload})")
    int insertUserPromotion(UserPromotion userPromotion);

    @Select("SELECT COUNT(*) FROM user_promotions WHERE user_id = #{userId} AND torrent_id = #{torrentId}")
    boolean existsByUserAndTorrent(@Param("userId") Long userId, @Param("torrentId") Long torrentId);

    // 用户查询自己领取的奖励
    // 查询自己领取的促销奖励（带种子名）
    @Select("""
        SELECT up.id, up.user_id, up.torrent_id, t.name AS torrent_name,
               up.promotion_type, up.bonus_credit, up.bonus_upload, up.bonus_download, up.created_at
        FROM user_promotions up
        JOIN torrents t ON up.torrent_id = t.id
        WHERE up.user_id = #{userId}
        ORDER BY up.created_at DESC
        LIMIT #{offset}, #{pageSize}
    """)
    List<UserPromotion> getUserPromotionsPaged(@Param("userId") Long userId,
                                               @Param("offset") int offset,
                                               @Param("pageSize") int pageSize);

    // 查询总数（分页用）
    @Select("SELECT COUNT(*) FROM user_promotions WHERE user_id = #{userId}")
    int countUserPromotions(@Param("userId") Long userId);

    // 查询所有用户领取的促销奖励（管理员查看，分页）
    @Select("""
    SELECT up.id, up.user_id, u.username, up.torrent_id, t.name AS torrent_name,
           up.promotion_type, up.bonus_credit, up.bonus_upload, up.bonus_download, up.created_at
    FROM user_promotions up
    JOIN users u ON up.user_id = u.id
    JOIN torrents t ON up.torrent_id = t.id
    ORDER BY up.created_at DESC
    LIMIT #{offset}, #{pageSize}
""")
    List<Map<String, Object>> getAllUserPromotionsPaged(@Param("offset") int offset,
                                                        @Param("pageSize") int pageSize);

    // 查询总数（管理员分页用）
    @Select("SELECT COUNT(*) FROM user_promotions")
    int countAllUserPromotions();


}
